package com.xydtech.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xydtech.common.annotation.Log;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.system.domain.SysPost;
import com.xydtech.system.service.ISysPostService;
import com.xydtech.workflow.domain.WflApprauthor;
import com.xydtech.workflow.domain.WflFlowstep;
import com.xydtech.workflow.service.IWflApprauthorService;
import com.xydtech.workflow.service.IWflFlowstepService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 流程节点配置Controller
 *
 * @author JHON
 * @date 2021-05-07
 */
@Controller
@RequestMapping("/workflow/flowstep")
public class WflFlowstepController extends BaseController {
    private String prefix = "workflow/flowstep";

    @Autowired
    private IWflFlowstepService wflFlowstepService;
    @Autowired
    private IWflApprauthorService wflApprauthorService;
    @Autowired
    private ISysPostService sysPostService;

    /**
     * 新增保存流程节点配置
     */
    @RequiresPermissions("workflow:flowdefine:add")
    @Log(title = "新增流程节点", businessType = BusinessType.INSERT)
    @PostMapping("/addStep")
    @ResponseBody
    public AjaxResult addStep(Long versionId, String stepJson) {
        try {
            //先查询原有选择的流程节点
            List<WflFlowstep> oldStepList = wflFlowstepService.selectWflFlowstepById(versionId);
            //加工新增节点list
            JSONArray addStepJson = JSON.parseArray(stepJson);
            List<WflFlowstep> addStepList = new ArrayList();
            for (int i = 0; i < addStepJson.size(); i++) {
                WflFlowstep wflFlowstep = new WflFlowstep();
                wflFlowstep.setVersionId(versionId);
                wflFlowstep.setStepId(Long.valueOf(addStepJson.getJSONObject(i).getString("stepId")));
                //顺序号需要叠加原来已经选择的节点数
                wflFlowstep.setOrderNum((long) (oldStepList.size() + i + 1));
                //节点类型 1-起始节点 2-中间节点 3-结束节点
                if (i == 0 && oldStepList.size() == 0) {
                    wflFlowstep.setStepType("1");
                } else if (i == addStepJson.size() - 1) {
                    wflFlowstep.setStepType("3");
                } else {
                    wflFlowstep.setStepType("2");
                }
                addStepList.add(wflFlowstep);
            }
            //更新原有结束节点类型为中间节点
            wflFlowstepService.updateWflFlowstepType(versionId);
            //批量新增节点
            wflFlowstepService.insertWflFlowstep(addStepList);
            //初始化流程审批权限数据
            wflApprauthorService.insertWflApprauthor(versionId);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 修改保存流程节点配置
     */
    @RequiresPermissions("workflow:flowdefine:edit")
    @Log(title = "流程节点配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WflFlowstep wflFlowstep) {
        try {
            wflFlowstep.setSts("1");
            wflFlowstepService.updateWflFlowstep(wflFlowstep);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 删除流程节点配置
     */
    @RequiresPermissions("workflow:flowdefine:remove")
    @Log(title = "删除流程节点", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(Long versionId, String stepJson) {
        try {
            //先查询原有选择的流程节点
            List<WflFlowstep> oldSteplist = wflFlowstepService.selectWflFlowstepById(versionId);
            //加工移除节点
            List<WflFlowstep> removeStepList = new ArrayList();
            JSONArray removeStepJson = JSON.parseArray(stepJson);
            //流程不能少于两个节点
            if (oldSteplist.size() - removeStepJson.size() < 2) {
                return error("流程剩余节点不能少于两个！");
            }
            for (int i = 0; i < removeStepJson.size(); i++) {
                WflFlowstep wflFlowstep = new WflFlowstep();
                wflFlowstep.setStepId(Long.valueOf(removeStepJson.getJSONObject(i).getString("stepId")));
                removeStepList.add(wflFlowstep);
            }
            //批量删除节点信息
            wflFlowstepService.deleteWflFlowstepByVersionIdAndStepIds(versionId, removeStepList);

            //查询最新的流程节点
            List<WflFlowstep> newSteplist = wflFlowstepService.selectWflFlowstepById(versionId);
            if (newSteplist.size() > 0) {
                //循环遍历，重新设置节点顺序和类型
                List<WflFlowstep> lastSteplist = new ArrayList<>();
                for (int j = 0; j < newSteplist.size(); j++) {
                    WflFlowstep wflFlowstep = new WflFlowstep();
                    wflFlowstep = newSteplist.get(j);
                    wflFlowstep.setOrderNum((long) (j + 1));
                    //节点类型 1-起始节点 2-中间节点 3-结束节点
                    if (j == 0) {
                        wflFlowstep.setStepType("1");
                    } else if (j == newSteplist.size() - 1) {
                        wflFlowstep.setStepType("3");
                    } else {
                        wflFlowstep.setStepType("2");
                    }
                    lastSteplist.add(wflFlowstep);
                }
                //批量更新流程节点信息
                wflFlowstepService.bathUpdateWflFlowstep(lastSteplist);
                //更新流程审批权限数据
                wflApprauthorService.insertWflApprauthor(versionId);
            }

            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 上移流程节点
     */
    @RequiresPermissions("workflow:flowdefine:edit")
    @Log(title = "上移流程节点", businessType = BusinessType.UPDATE)
    @PostMapping("/up")
    @ResponseBody
    public AjaxResult upStep(Long versionId, Long stepId, Long orderNum) {
        try {
            /**根据被替换节点顺序先修改被替换位置节点信息*/
            //查询流程节点
            List<WflFlowstep> oldSteplist = wflFlowstepService.selectWflFlowstepById(versionId);
            WflFlowstep lastWflFlowstep = new WflFlowstep();
            lastWflFlowstep.setVersionId(versionId);
            //被替换节点顺序为当前节点序号减1
            lastWflFlowstep.setOrderNum(orderNum - 1);
            //被替换节点移动后的序号等于当前节点序号，如果当前节点为最后节点，被替换节点类型为3-结束节点，否则为2-中间节点
            if (orderNum == oldSteplist.size()) {
                lastWflFlowstep.setStepType("3");
            } else {
                lastWflFlowstep.setStepType("2");
            }
            //修改被替换位置节点顺序号
            wflFlowstepService.updateUpstepOrderNumByVersionIdAndOrderNum(lastWflFlowstep);

            /**开始修改上移节点*/
            WflFlowstep wflFlowstep = new WflFlowstep();
            wflFlowstep.setVersionId(versionId);
            wflFlowstep.setStepId(stepId);
            //上移一次顺序号减1，如果上移到第一位节点类型为1-开始节点，否则为2-中间节点
            wflFlowstep.setOrderNum(orderNum - 1);
            if (orderNum - 1 == 1) {
                wflFlowstep.setStepType("1");
            } else {
                wflFlowstep.setStepType("2");
            }
            //修改当前上移节点顺序及节点类型
            wflFlowstepService.updateWflFlowstep(wflFlowstep);

            //更新流程审批权限数据
            wflApprauthorService.insertWflApprauthor(versionId);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 下移流程节点
     */
    @RequiresPermissions("workflow:flowdefine:edit")
    @Log(title = "下移流程节点", businessType = BusinessType.UPDATE)
    @PostMapping("/down")
    @ResponseBody
    public AjaxResult downStep(Long versionId, Long stepId, Long orderNum) {
        try {

            //查询流程节点
            List<WflFlowstep> oldSteplist = wflFlowstepService.selectWflFlowstepById(versionId);
            if (oldSteplist.size() == orderNum) {
                return error("当前节点为最后一个节点，无法下移！");
            }
            /**根据被替换节点顺序先修改被替换位置节点信息*/
            WflFlowstep nextWflFlowstep = new WflFlowstep();
            nextWflFlowstep.setVersionId(versionId);
            //被替换节点顺序为当前节点序号加1
            nextWflFlowstep.setOrderNum(orderNum + 1);
            //被替换节点移动后的序号等于当前节点序号，如果当前节点为开始节点，被替换节点类型为1-开始节点，否则为2-中间节点
            if (orderNum == 1) {
                nextWflFlowstep.setStepType("1");
            } else {
                nextWflFlowstep.setStepType("2");
            }
            //修改被替换位置节点顺序号
            wflFlowstepService.updateDownstepOrderNumByVersionIdAndOrderNum(nextWflFlowstep);

            /**开始修改下移节点*/
            WflFlowstep wflFlowstep = new WflFlowstep();
            wflFlowstep.setVersionId(versionId);
            wflFlowstep.setStepId(stepId);
            //下移一次顺序号加1，如果上移到第一位节点类型为1-开始节点，否则为2-中间节点
            wflFlowstep.setOrderNum(orderNum + 1);
            if (orderNum + 1 == oldSteplist.size()) {
                wflFlowstep.setStepType("3");
            } else {
                wflFlowstep.setStepType("2");
            }
            //修改当前上移节点顺序及节点类型
            wflFlowstepService.updateWflFlowstep(wflFlowstep);

            //更新流程审批权限数据
            wflApprauthorService.insertWflApprauthor(versionId);
            return success();
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     *获取任务定位下拉框数据
     * @Title: taskIndexStr
     * @param taskMode
     * @param versionId
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author JHON
     * @Date 2021/5/28 16:26
     **/
    @RequiresPermissions("workflow:flowdefine:view")
    @PostMapping("/taskindex")
    @ResponseBody
    public AjaxResult taskIndexStr(String taskMode, Long versionId, Long orderNum, String taskIndex) {
        try {
            StringBuilder taskIndexStr = new StringBuilder().append("'<option value=\"\">请选择任务定位</option>'");
            //如果是选人员，则查询关联步骤;
            if ("1".equals(taskMode)) {
                List<WflFlowstep> stepList = wflApprauthorService.selectApprBackStep(versionId, orderNum);
                if (stepList.size() > 0) {
                    for (int i = 0; i < stepList.size(); i++) {
                        if (taskIndex.equals(stepList.get(i).getStepId().toString())) {
                            taskIndexStr.append("'<option value=\"" + stepList.get(i).getStepId() + "\" selected=\"selected\">" + stepList.get(i).getStepName() + "</option>'");
                        } else {
                            taskIndexStr.append("'<option value=\"" + stepList.get(i).getStepId() + "\">" + stepList.get(i).getStepName() + "</option>'");
                        }
                    }
                }
            } else {
                //选岗位查询岗位列表
                SysPost post = new SysPost();
                post.setStatus("0");
                List<SysPost> postList = sysPostService.selectPostList(post);
                if (postList.size() > 0) {
                    for (int i = 0; i < postList.size(); i++) {
                        if (taskIndex.equals(postList.get(i).getPostId().toString())) {
                            taskIndexStr.append("'<option value=\"" + postList.get(i).getPostId() + "\" selected=\"selected\">" + postList.get(i).getPostName() + "</option>'");
                        } else {
                            taskIndexStr.append("'<option value=\"" + postList.get(i).getPostId() + "\">" + postList.get(i).getPostName() + "</option>'");
                        }
                    }
                }
            }
            return success(taskIndexStr.toString());
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 查询流程节点的审批配置信息
     * @Title: wflApprovInfo
     * @param versionId
     * @param orderNum
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author JHON
     * @Date 2021/5/31 18:02
     **/
    @RequiresPermissions("workflow:flowdefine:view")
    @PostMapping("/wflapprovinfo")
    @ResponseBody
    public AjaxResult wflApprovInfo(Long versionId, Long orderNum) {
        try {
            WflFlowstep wflFlowstep = new WflFlowstep();
            wflFlowstep = wflFlowstepService.selectWflFlowstepByVersionIdAndOrderNum(versionId, orderNum);
            return success(JSON.toJSONString(wflFlowstep, SerializerFeature.WriteMapNullValue));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 查询节点审批权限列表
     * @Title: wflApprovList
     * @param versionId
     * @param stepId
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author JHON
     * @Date 2021/5/31 18:03
     **/
    @RequiresPermissions("workflow:flowdefine:view")
    @PostMapping("/wflapprovlist")
    @ResponseBody
    public AjaxResult wflApprovList(Long versionId, Long stepId) {
        try {
            List<WflApprauthor> list = wflApprauthorService.selectWflApprauthorList(versionId, stepId);
            return success(JSON.toJSONString(list, SerializerFeature.WriteMapNullValue));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }
}
